var rootuserid = 0;
var lowerid = 0, lastlowerid = 0;
var totalAmount = 0, totalAmountUsed = 0;

var maxGiveBackOfNewAccount = 0.03;
var minSpanBackPct = 0.005;
var maxBackPct = 0;

jQuery(document).ready(function () {
    getMaxBackPct();
    $j('#tabs').tabs(); 
    lowerid = rootuserid;
    jQuery("#tb_list").jqGrid({
        url: '/ajax.aspx?oper=jqgrid&jqgoper=getlowerlist&lowerid=' + lowerid + '&firstrequest=1&nd=' + new Date().getTime(),
        datatype: "json",
        colNames: ['用户名','返点%', '总金币', '冻结金币', '可用金币', '最后登录时间', '状态', '在线'],
        colModel: [
        { name: 'username', width: 100, searchoptions: { sopt: ["eq"]} },
    	{ name: 'backpct', width: 80, align: "center", sortable: false, search: false },
        { name: 'amount', width: 100, align: "right", search: false },
        { name: 'amountused', width: 100, align: "right", search: false },
        { name: 'amountlave', width: 100, align: "right", search: false },
        { name: 'lasttime', width: 120, align: "center", search: false },
        { name: 'status', width: 60, align: "center", search: false },
        { name: 'online', width: 50, align: "center", sortable: false, search: false }],
        pager: "#div_page",
        rowNum: 20,
        rowList: [20, 50, 100],
        height: 460,
        viewrecords: true,
        footerrow: true,
        sortname: "id",
        sortorder: "asc",
        caption: "<a href='javascript:void(0)' onclick='showLowerList(" + rootuserid + ")'>本级</a>",
        editurl: "#",
        loadJSONDataComplete: function (a) {             //服务端数据格式 username,realname,amount,amountused,usertype,lasttime,[status],onlineuserid,giveback
            if (a && a.rows && a.rows.length > 0) {
                var pos = (a.page - 1) * jQuery("#tb_list").jqGrid()[0].p.rowNum + 1;
                var sum_amount = 0, sum_amountused = 0;
                var amount, amountused, amountlave;
                var index = 0;
                for (var i = 0; i < a.rows.length; i++) {
                    var newcell = new Array();
                    index = 0;
                    newcell[index++] = pos++;
                    newcell[index++] = "<a href='javascript:void(0)' title='" + a.rows[i].cell[1] + "' onclick='showLowerList(" + a.rows[i].id + ")'>" + a.rows[i].cell[0] + "</a>";
                    newcell[index++] = getUserTypeHtml(a.rows[i].cell[4]);
                    newcell[index++] = parseFloat(a.rows[i].cell[8] * 100).toFixed(2);
                    amount = parseFloat(a.rows[i].cell[2]);
                    sum_amount += amount;
                    amountused = parseFloat(a.rows[i].cell[3]);
                    sum_amountused += amountused;
                    amountlave = amount - amountused;
                    newcell[index++] = amount.toFixed(2);
                    newcell[index++] = amountused.toFixed(2);
                    newcell[index++] = amountlave.toFixed(2);
                    newcell[index++] = a.rows[i].cell[5];
                    newcell[index++] = getUserStatusHtml(a.rows[i].cell[6], a.rows[i].id);
                    newcell[index++] = getOnlineStatusHtml(a.rows[i].cell[7]);
                    //newcell[index++] = (rootuserid == a.rows[i].id) ? "" : "<input type=\"button\" value=\"修改\" onclick=\"modify(" + a.rows[i].id + ")\" /> " + getStatusButtonHtml(a.rows[i].cell[6], a.rows[i].id) + " <input type=\"button\" value=\"删除\" onclick=\"dellower(" + a.rows[i].id + ")\" />";
                    newcell[index++] = "";
                    a.rows[i].cell = newcell;
                }
                if (a.totalDatas) {
                    totalAmount = parseFloat(a.totalDatas[0][0]);
                    totalAmountUsed = parseFloat(a.totalDatas[0][1]);
                    //重新设置URL
                    if (a.lowerid && a.lowerid != lowerid)
                        lowerid = a.lowerid;
                    var newurl = "";
                    if ($("#cbxSum").attr("checked")) {
                        //汇总显示
                        newurl = '/ajax.aspx?oper=jqgrid&jqgoper=getlowerlist&lowerid=' + lowerid + '&firstrequest=0&issum=1&nd=' + new Date().getTime();

                    }
                    else {
                        //普通显示
                        newurl = '/ajax.aspx?oper=jqgrid&jqgoper=getlowerlist&lowerid=' + lowerid + '&firstrequest=0&issum=0&nd=' + new Date().getTime();
                    }
                    jQuery("#tb_list").jqGrid("setGridParam", { url: newurl });
                }
                jQuery("#tb_list").jqGrid("footerData", "set", { username: "本页小计<br />总合计", amount: sum_amount.toFixed(2) + "<br />" + totalAmount.toFixed(2), amountused: sum_amountused.toFixed(2) + "<br />" + totalAmountUsed.toFixed(2), amountlave: parseFloat(sum_amount - sum_amountused).toFixed(2) + "<br />" + parseFloat(totalAmount - totalAmountUsed).toFixed(2) });
                if (lowerid == rootuserid) {
                    //显示本级时，恢复导航栏
                    jQuery("#tb_list").jqGrid("setCaption", "<a href='javascript:void(0)' onclick='showLowerList(" + rootuserid + ")'>本级</a>");
                }
                if (a.navDatas && a.navDatas.length > 0) {
                    var html = "<a href='javascript:void(0)' onclick='showLowerList(" + rootuserid + ")'>本级</a>";
                    for (var i = 0; i < a.navDatas.length; i++) {
                        //最底层，不加链接
                        if (i == (a.navDatas.length - 1))
                            html += " > " + a.navDatas[i][1];
                        else
                            html += " > <a href='javascript:void(0)' onclick='showLowerList(" + a.navDatas[i][0] + ")'>" + a.navDatas[i][1] + "</a>";
                    }
                    jQuery("#tb_list").jqGrid("setCaption", html);
                }
            }
        },
        onSelectRow: function (id) {
            if (id) {
                jQuery('#' + id).removeClass("ui-state-highlight");
                //alert(jQuery("#tb_list").jqGrid("getRowData", id).amount);
            }
        } });
    jQuery("#tb_list").jqGrid('navGrid', '#div_page', { edit: false, add: false, del: false }, {}, {}, {}, { closeOnEscape: true });
    
    jQuery("#tb_list2").jqGrid({
        url: '/ajax.aspx?oper=jqgrid&jqgoper=getlowerlist&lowerid=' + lowerid + '&firstrequest=1&nd=' + new Date().getTime(),
        datatype: "json",
        colNames: ['用户名','游戏类型', '开奖号码', '下注类型','下注金额', '结果','返点%', '我的奖金'], 
        colModel: [
        { name: 'username', width: 100, searchoptions: { sopt: ["eq"]} },
    	{ name: 'backpct', width: 80, align: "center", sortable: false, search: false },
        { name: 'amount', width: 100, align: "right", search: false },
        { name: 'amountused', width: 100, align: "right", search: false },
        { name: 'amountlave', width: 100, align: "right", search: false },
        { name: 'lasttime', width: 120, align: "center", search: false },
        { name: 'status', width: 60, align: "center", search: false },
        { name: 'online', width: 50, align: "center", sortable: false, search: false }],
        pager: "#div_page",
        rowNum: 20,
        rowList: [20, 50, 100],
        height: 460,
        viewrecords: true,
        footerrow: true,
        sortname: "id",
        sortorder: "asc",
        caption: "<a href='javascript:void(0)' onclick='showLowerList(" + rootuserid + ")'>本级</a>",
        editurl: "#",
        loadJSONDataComplete: function (a) {             //服务端数据格式 username,realname,amount,amountused,usertype,lasttime,[status],onlineuserid,giveback
            if (a && a.rows && a.rows.length > 0) {
                var pos = (a.page - 1) * jQuery("#tb_list").jqGrid()[0].p.rowNum + 1;
                var sum_amount = 0, sum_amountused = 0;
                var amount, amountused, amountlave;
                var index = 0;
                for (var i = 0; i < a.rows.length; i++) {
                    var newcell = new Array();
                    index = 0;
                    newcell[index++] = pos++;
                    newcell[index++] = "<a href='javascript:void(0)' title='" + a.rows[i].cell[1] + "' onclick='showLowerList(" + a.rows[i].id + ")'>" + a.rows[i].cell[0] + "</a>";
                    newcell[index++] = getUserTypeHtml(a.rows[i].cell[4]);
                    newcell[index++] = parseFloat(a.rows[i].cell[8] * 100).toFixed(2);
                    amount = parseFloat(a.rows[i].cell[2]);
                    sum_amount += amount;
                    amountused = parseFloat(a.rows[i].cell[3]);
                    sum_amountused += amountused;
                    amountlave = amount - amountused;
                    newcell[index++] = amount.toFixed(2);
                    newcell[index++] = amountused.toFixed(2);
                    newcell[index++] = amountlave.toFixed(2);
                    newcell[index++] = a.rows[i].cell[5];
                    newcell[index++] = getUserStatusHtml(a.rows[i].cell[6], a.rows[i].id);
                    newcell[index++] = getOnlineStatusHtml(a.rows[i].cell[7]);
                    //newcell[index++] = (rootuserid == a.rows[i].id) ? "" : "<input type=\"button\" value=\"修改\" onclick=\"modify(" + a.rows[i].id + ")\" /> " + getStatusButtonHtml(a.rows[i].cell[6], a.rows[i].id) + " <input type=\"button\" value=\"删除\" onclick=\"dellower(" + a.rows[i].id + ")\" />";
                    newcell[index++] = "";
                    a.rows[i].cell = newcell;
                }
                if (a.totalDatas) {
                    totalAmount = parseFloat(a.totalDatas[0][0]);
                    totalAmountUsed = parseFloat(a.totalDatas[0][1]);
                    //重新设置URL
                    if (a.lowerid && a.lowerid != lowerid)
                        lowerid = a.lowerid;
                    var newurl = "";
                    if ($("#cbxSum").attr("checked")) {
                        //汇总显示
                        newurl = '/ajax.aspx?oper=jqgrid&jqgoper=getlowerlist&lowerid=' + lowerid + '&firstrequest=0&issum=1&nd=' + new Date().getTime();

                    }
                    else {
                        //普通显示
                        newurl = '/ajax.aspx?oper=jqgrid&jqgoper=getlowerlist&lowerid=' + lowerid + '&firstrequest=0&issum=0&nd=' + new Date().getTime();
                    }
                    jQuery("#tb_list").jqGrid("setGridParam", { url: newurl });
                }
                jQuery("#tb_list").jqGrid("footerData", "set", { username: "本页小计<br />总合计", amount: sum_amount.toFixed(2) + "<br />" + totalAmount.toFixed(2), amountused: sum_amountused.toFixed(2) + "<br />" + totalAmountUsed.toFixed(2), amountlave: parseFloat(sum_amount - sum_amountused).toFixed(2) + "<br />" + parseFloat(totalAmount - totalAmountUsed).toFixed(2) });
                if (lowerid == rootuserid) {
                    //显示本级时，恢复导航栏
                    jQuery("#tb_list").jqGrid("setCaption", "<a href='javascript:void(0)' onclick='showLowerList(" + rootuserid + ")'>本级</a>");
                }
                if (a.navDatas && a.navDatas.length > 0) {
                    var html = "<a href='javascript:void(0)' onclick='showLowerList(" + rootuserid + ")'>本级</a>";
                    for (var i = 0; i < a.navDatas.length; i++) {
                        //最底层，不加链接
                        if (i == (a.navDatas.length - 1))
                            html += " > " + a.navDatas[i][1];
                        else
                            html += " > <a href='javascript:void(0)' onclick='showLowerList(" + a.navDatas[i][0] + ")'>" + a.navDatas[i][1] + "</a>";
                    }
                    jQuery("#tb_list").jqGrid("setCaption", html);
                }
            }
        },
        onSelectRow: function (id) {
            if (id) {
                jQuery('#' + id).removeClass("ui-state-highlight");
                //alert(jQuery("#tb_list").jqGrid("getRowData", id).amount);
            }
        } });
    jQuery("#tb_list2").jqGrid('navGrid', '#div_page', { edit: false, add: false, del: false }, {}, {}, {}, { closeOnEscape: true });
    
    $j("#lowerdialog").dialog({ autoOpen: false,
        width: 280,
        minHeight: 160,
        modal: true,
        resizable: false,
        close: function (event, ui) {
            $j("#divusertype").show();
            $("#tbUserName").attr("readonly", false);
            $("#divpassword").show();
            $("#divpassword1").show();
            $("#tbUserName").val("");
            $("#tbRealName").val("");
            $("#tbPassword").val("");
            $("#tbPassword1").val("");
            $("#spanBackPct").html("0.00");
            $("#spanBackPctDesc").show();
            $("#lisubbackpct").show();
            $("#msg").html("");
        }
    });
    $j("#div_dialog_confirm").dialog({ title: "提示信息", autoOpen: false, modal: true, resizable: false });
    $j('ul#icons li').hover(
					function () { $(this).addClass('ui-state-hover'); },
					function () { $(this).removeClass('ui-state-hover'); }
				);
});
function chgSum() {
    var newurl = "";
    if ($("#cbxSum").attr("checked")) {
        //汇总显示
        newurl = '/ajax.aspx?oper=jqgrid&jqgoper=getlowerlist&lowerid=' + lowerid + '&firstrequest=1&issum=1&nd=' + new Date().getTime();

    }
    else {
        //普通显示
        newurl = '/ajax.aspx?oper=jqgrid&jqgoper=getlowerlist&lowerid=' + lowerid + '&firstrequest=1&issum=0&nd=' + new Date().getTime();
    }
    jQuery("#tb_list").jqGrid("setGridParam", { url: newurl });
    reloadData();
}
function changestatus(chgid) {
    $.post("ajax_lowerlock.aspx", { lowerid: chgid }, changestatuscomplete);
}

function changestatuscomplete(data) {
    if (data == "") {
        showErrorMsg("修改锁定失败");
        return;
    }
    var result;
    try {
        eval("result=" + data);
    }
    catch (e) {
        showErrorMsg("修改锁定失败");
        return;
    }
    if (!result) {
        showErrorMsg("修改锁定失败");
        return;
    }
    if (result.status) {
        var tempdata;
        eval("tempdata=" + result.msg);
        if (tempdata.length != 2) {
            showErrorMsg("修改锁定失败");
            return;
        }
        if (tempdata[0] == "0") {
            $("#btnchg" + tempdata[1])[0].value = "锁定";
            $("#sp_" + tempdata[1])[0].innerText = "激活";
            $("#sp_" + tempdata[1])[0].className = "greenfont";
        }
        else {
            $("#btnchg" + tempdata[1])[0].value = "激活";
            $("#sp_" + tempdata[1])[0].innerText = "锁定";
            $("#sp_" + tempdata[1])[0].className = "redfont";
        }
    }
    else {
        showErrorMsg(result.msg);
    }
}
function getOnlineStatusHtml(onlineuserid) {
    //根据在线ID获取对应html
    try {
        if (parseInt(onlineuserid) > 0)
            return "<img src='images/online.gif' alt='' />";
        else
            return "<img src='images/offline.gif' alt='' />";
    }
    catch (e) {
        return "<img src='images/offline.gif' alt='' />";
    }
}
function getUserStatusHtml(userstatus, id) {
    //根据用户状态获取对应html
    try {
        if (parseInt(userstatus) == 0)
            return "<span id='sp_" + id + "' class='greenfont'>激活</span>";
        else
            return "<span id='sp_" + id + "' class='redfont'>锁定</span>";
    }
    catch (e) {
        return "<span id='sp_" + id + "' class='greenfont'>锁定</span>";
    }
}
function getStatusButtonHtml(status, id) {
    if (status == "0")
        return "<input id=\"btnchg" + id + "\" type=\"button\" value=\"锁定\" onclick=\"changestatus(" + id + ")\" />";
    return "<input id=\"btnchg" + id + "\" type=\"button\" value=\"激活\" onclick=\"changestatus(" + id + ")\" />";
}
function dellower(userid) {
    var data = jQuery("#tb_list").jqGrid("getRowData", userid);
    if (data == null)
        return;
    $("#div_dialog_confirm").dialog("option", "title", "确认删除");
    $("#div_dialog_confirm").dialog("option", "buttons", { "确认": function () {
        $("#div_dialog_confirm").dialog("option", "title", "处理中......");
        $("#div_dialog_confirm").dialog("option", "buttons", "");
        $("#div_dialog_confirm").html(htmlload);
        $.post("ajax_lowerdel.aspx", { lowerid: userid }, completeLowerDel);
    }, "取消": function () { $(this).dialog("close"); }
    });
    $("#div_dialog_confirm").html("账号:" + jQuery(data.username)[0].innerHTML + "<br />类型:" + jQuery(data.usertype)[0].innerHTML + "<br />是否删除?");
    $("#div_dialog_confirm").dialog("open");
}
var htmlload = "<table style='width:100%;height:100%;'><tr><td style='text-align:center;background-color:transparent;'><img src='images/bigloading.gif' alt=''/></td></tr></table>";

function completeLowerDel(data) {
    if (data == "") {
        showErrorMsg("删除失败");
        return;
    }
    var result;
    eval("result=" + data);
    if (!result) {
        showErrorMsg("删除失败");
        return;
    }
    if (result.status) {
        reloadData();
        $("#div_dialog_confirm").dialog("close");
    }
    else {
        showErrorMsg(result.msg);
    }
}
function reloadData() {
    jQuery("#tb_list").jqGrid().trigger("reloadGrid");
}
function showLowerList(id) {
    //alert(jQuery("tr.sf td.data INPUT").val(""));     搜索输入框
    //jQuery("tr.sf td.data INPUT").val("");      //清除搜索框    
    //显示用户列表
    if (lowerid != id) {
        //新用户，需要申请合计栏及导航栏
        lowerid = id;
        chgSum();
        reloadData();
    }
}
function addnewmember(data) {
    $j("#lowerdialog").dialog("option", "title", "添加下级");
    $j("#lowerdialog").dialog("option", "buttons", {
        "添加": function () {
            //添加会员
            var username = $("#tbUserName").val().replace(/\s/g, "");
            if (username == "") {
                $("#msg").html("用户名不能为空");
                return;
            }
            if (username.length > 20) {
                $("#msg").html("用户名过长(10字符以内)");
                return;
            }
            var realname = $("#tbRealName").val().replace(/\s/g, "");
            if (realname.length > 20) {
                $("#msg").html("昵称过长(10字符以内)");
                return;
            }
            var password = $("#tbPassword").val().replace(/\s/g, "");
            if (password == "") {
                $("#msg").html("密码不能为空");
                return;
            }
            if (password.length < 6) {
                $("#msg").html("密码太短(6位以上)");
                return;
            }
            var password1 = $("#tbPassword1").val().replace(/\s/g, "");
            if (password != password1) {
                $("#msg").html("两次输入的密码不一致");
                return;
            }
            var backpct = parseFloat($("#spanBackPct").html());
            if (isNaN(backpct)) {
                $("#msg").html("返点输入有误");
                return;
            }
            backpct /= 100;
            var usertype = $("input[name='rbtType'][checked]").val();
            $.post("ajax_loweradd.aspx", { username: username, realname: realname, password: password, backpct: backpct, usertype: usertype }, completeLowerAdd);
            $j("#dialogmain").hide();
            $j("#divloading").show();
        }, "取消": function () {
            $j(this).dialog("close");
        }
    });
    $j("#dialogmain").show();
    $j("#divloading").hide();
    $j("#lowerdialog").dialog("open");
}
function chgBackPct(fx) {
    var backPct = parseFloat($("#spanBackPct").html());
    if (isNaN(backPct))
        return;
    backPct /= 100;
    backPct += fx * minSpanBackPct;
    backPct = backPct.toFixed(4);
    if (backPct < 0 || backPct > maxBackPct)
        return;
    $("#spanBackPct").html((backPct * 100).toFixed(2));
}
function completeLowerAdd(data) {
    if (data == "") {
        $("#msg").html("提交失败");
        $("#dialogmain").show();
        $("#divloading").hide();
        return;
    }
    var tempdata;
    eval("tempdata=" + data);
    if (!tempdata) {
        $("#msg").html("提交失败");
        $("#dialogmain").show();
        $("#divloading").hide();
        return;
    }
    if (tempdata.status) {
        //成功
        reloadData();
        $("#lowerdialog").dialog("close");
    }
    else {
        //失败
        $("#msg").html(tempdata.msg);
        $("#dialogmain").show();
        $("#divloading").hide();
    }
}
function modify(lowerid) {
    if (userInfo == null)
        return;
    var userdata = jQuery("#tb_list").jqGrid("getRowData", lowerid);
    if (userdata == null)
        return;
    $("#divusertype").hide();
    $("#tbUserName").val($(userdata.username).html());
    $("#tbUserName").attr("readonly", true);
    $("#tbRealName").val($(userdata.username).attr("title"));
    $("#spanBackPct").html(userdata.backpct);
    $("#spanBackPctDesc").hide();
    $("#lisubbackpct").hide();
    if (userInfo.Aid != 0) {
        $("#divpassword").hide();
        $("#divpassword1").hide();
    }
    $("#lowerdialog").dialog("option", "title", "修改下级");
    $("#lowerdialog").dialog("option", "buttons", {
        "提交": function () {
            //修改会员
            var realname = $("#tbRealName").val().replace(/\s/g, "");
            if (realname.length > 20) {
                $("#msg").html("昵称过长(10字符以内)");
                return;
            }
            var password = $("#tbPassword").val().replace(/\s/g, "");
            if (password != "" && password.length < 6) {
                $("#msg").html("密码太短(6位以上)");
                return;
            }
            var password1 = $("#tbPassword1").val().replace(/\s/g, "");
            if (password != password1) {
                $("#msg").html("两次输入的密码不一致");
                return;
            }
            var backpct = parseFloat($("#spanBackPct").html());
            if (isNaN(backpct)) {
                $("#msg").html("返点输入有误");
                return;
            }
            backpct /= 100;
            $.post("ajax_loweredit.aspx", { lowerid: lowerid, realname: realname, password: password, backpct: backpct }, completeLowerEdit);
            $("#dialogmain").hide();
            $("#divloading").show();
        }, "取消": function () {
            $(this).dialog("close");
        }
    });
    $("#dialogmain").show();
    $("#divloading").hide();
    $("#lowerdialog").dialog("open");
}
function completeLowerEdit(data) {
    if (data == "") {
        $("#msg").html("提交失败");
        $("#dialogmain").show();
        $("#divloading").hide();
        return;
    }
    var tempdata;
    eval("tempdata=" + data);
    if (!tempdata) {
        $("#msg").html("提交失败");
        $("#dialogmain").show();
        $("#divloading").hide();
        return;
    }
    if (tempdata.status) {
        //成功
        reloadData();
        $("#lowerdialog").dialog("close");
    }
    else {
        //失败
        $("#msg").html(tempdata.msg);
        $("#dialogmain").show();
        $("#divloading").hide();
    }
}
function getMaxBackPct() {
    if (userInfo.UserName == "") {
        setTimeout(getMaxBackPct, 500);
        return;
    }
    maxBackPct = Math.max(userInfo.BackPct - minSpanBackPct, 0).toFixed(4);
    $("#spanBackPctDesc").html("0.00% - " + (maxBackPct * 100).toFixed(2) + "%");
}
function showErrorMsg(msg) {
    $("#div_dialog_confirm").html(msg);
    $("#div_dialog_confirm").dialog("open");
}


function showProfitRecords(id) {
    if (jQuery("#tabs").tabs("option", "selected") != 1)
        jQuery("#tabs").tabs("select", 1);
    if (needrequest2 || lowerid2 != id) {
        lowerid2 = id;
        needrequest2 = false;
        $('#tabs').tabs("select", 1);
        jQuery("#tb_list2").jqGrid("setGridParam", { url: getJQGridUrl2(), page: 1 }).trigger("reloadGrid");
        //jQuery("#tb_list").jqGrid('navGrid', '#div_page', { edit: false, add: false, del: false });
    }
}
function show_LowerList() {
    showLowerList(lowerid);
}
function showLowerList(id) {
    //显示用户列表
    if (jQuery("#tabs").tabs("option", "selected") != 0)
        jQuery("#tabs").tabs("select", 0);
    if (needrequest || lowerid != id) {
        //新用户，需要申请合计栏及导航栏
        lowerid = id;
        needrequest = false;
        jQuery("#tb_list").jqGrid("setGridParam", { url: getJQGridUrl(1), page: 1 }).trigger("reloadGrid");
    }
}